from flask import Blueprint, request
from utilsapp.mysql_con import  db_pagelist,db_delete,db_connect,db_connect
from utilsapp.common import assign_value, parsing_data_id
from utilsapp import utils
import pymysql
from flask import current_app

bluePrint = Blueprint('health', __name__)
tableName = 'health'



# 分页查询
@bluePrint.route('/getlist', methods=["post"])
def table_list():
    a=request.json
    start_time = assign_value(a, "start_time")
    end_time = assign_value(a, "end_time")
    device_id = assign_value(a,'device_id')
    if start_time != '':
        sql = f'''SELECT d.device_name,h.* from health h
LEFT JOIN device d on h.device_id = d.id
where d.id = {device_id} and time BETWEEN '{start_time}' and '{end_time}'
ORDER BY time desc'''
    else:
        sql = f'''SELECT d.device_name,h.* from health h
LEFT JOIN device d on h.device_id = d.id
where d.id = {device_id}
ORDER BY time desc'''
 
 
    j = db_pagelist(sql, request.json['page'],999)
    return j

@bluePrint.route('/liehua', methods=["post"])
def liehua():
    device_id = assign_value(request.json, "device_id")
    return utils.ok(get_device_imp(device_id))

def get_device_imp(device_id):
    """
    获取设备的预警信息和对应预测值的百分比。

    参数:
    - device_id: 设备ID，用于查询该设备的预警信息。

    返回值:
    - output_dict: 包含设备ID和每个通道(a、b、c)的预警信息及对应预测值的百分比的字典。
    """
    # 初始化预测字典列表，包含故障描述、预警代码和初始预测值（0）
    pred_dicts = [
        ["设备基础松动、变形，地脚松动", "BF02.001.7", 0],
        ["机组轴心线偏离，不对中", "UN01.002.1", 0],
        ["定转子气隙偏心，定转子刮擦", "MC01.001.1", 0],
        ["转子鼠笼条松动，断裂，变形", "MC01.003.1", 0],
        ["转子不平衡，主轴变形、弯曲", "MC01.006.1", 0],
        ["轴承内、外圈松动、开裂，以及剥落故障", "BF03.001.1", 0],
        ["线圈绝缘劣化", "MC01.005", 0],
        ["润滑脂、润滑油不足", "BF04.002.1", 0],
        ["定子齿槽松动，线圈松动，线圈端部松动", "MC01.002.1", 0],
        ["联轴器同轴度", "UN01.002.2", 0],
        ["轴承滚动体损伤、剥落", "BF03.002.1", 0],
        ["联轴器开裂，松动，窜动", "UN01.003.1", 0],
        ["电机的负载模式", "MC01.007.1", 0],
        ["隐性潜在故障或复合性故障", "MC01.100.1", 0],
        ["转子条裂纹可能在发展或高阻节点问题", "CM01", 0]
    ]
    # 定义通道列表
    Channls = ["aAmpere","bAmpere","cAmpere"]
    # 提取预警代码
    warn_codes = [p[1] for p in pred_dicts]
    # 构造SQL查询语句，获取未处理的预警信息
    sql = f"select * from warn where device_id = {device_id} and is_show = 1 and is_handled = 0"
    # 执行SQL查询
    settings = current_app.config['settings']['mysql']
    con = pymysql.connect(host=settings["host"], user=settings["user"], password=settings["password"],
                          database=settings["dbname"], port=(settings["port"]))
    cur = con.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    # 初始化存储预警信息的字典
    warn_dict = {}
    for i in Channls:
        warn_dict[i] = {}
        for j in warn_codes:
            warn_dict[i][j] = []
    # 处理查询结果，将预警信息分类存储
    for row in result:
        channl = row[2].split("|")[-1]
        if channl not in Channls:
            continue
        code = row[2].split("|")[-2]
        pred_data = row[19]
        if "CM01" in code:
            warn_dict[channl]["CM01"].append(pred_data)
        else:
            warn_dict[channl][code].append(pred_data)
    # 构造最终输出的字典
    output_dict = {"device_id": device_id}
    for i,channl in zip(["dataA", "dataB", "dataC"],Channls):
        # 根据通道和预警代码，计算每个预警项的预测值百分比
        pred_dicts_0 = pred_dicts.copy()
        for j,code in enumerate(pred_dicts_0):
            code=code[1]
            if not warn_dict[channl][code]:
                pred_dicts_0[j][2] = 0
            else:
                pred_dicts_0[j][2] = int(100 * max(warn_dict[channl][code]))
        output_dict[i] = pred_dicts_0
    return output_dict